package com.infodms.dms.actions.sales.marketmanage.planissued;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.common.FileUploadManager;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.marketmanage.plancommon.ActivitiesCommonDao;
import com.infodms.dms.dao.sales.marketmanage.planissued.ActivitiesSummaryIssuedDao;
import com.infodms.dms.dao.sales.marketmanage.planmanage.ActivitiesPlanManageDao;
import com.infodms.dms.dao.sales.planmanage.SpacePlanReportDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TtCamCampaignCostPO;
import com.infodms.dms.po.TtCamMediaCostPO;
import com.infodms.dms.po.TtCampaignExecuteChkPO;
import com.infodms.dms.po.TtCampaignExecutePO;
import com.infodms.dms.po.TtCampaignPO;
import com.infodms.dms.po.TtCampaignPoseChkRPO;
import com.infodms.dms.po.TtCampaignSpaceExecutePO;
import com.infodms.dms.po.TtCampaignSummeryChkPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

public class ActivitiesSummaryOemCheck {
	
	public Logger logger = Logger.getLogger(ActivitiesSummaryOemCheck.class);   
	ActivitiesSummaryIssuedDao dao  = ActivitiesSummaryIssuedDao.getInstance();
	private ActionContext act = ActionContext.getContext();
	
	private final String initUrl = "/jsp/sales/marketmanage/planissued/activitiesSummaryOemCheck.jsp";
	private final String addUrl = "/jsp/sales/marketmanage/planissued/activitiesSummaryOemCheckDetial.jsp";
	
	/**
	 * 活动执行方案提报页面初始化
	 */
	public void activitiesSummaryOemCheckQueryInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			act.setOutData("areaList", areaList);
			act.setForword(initUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动方案提报页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动执行方案提报查询
	 */
	public void activitiesSummaryOemCheckQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			Long poseId = logonUser.getPoseId() ;
			
			TtCampaignPoseChkRPO tcpcrp = new TtCampaignPoseChkRPO();
			tcpcrp.setPoseId(poseId);			
			List list = dao.select(tcpcrp);
			if(!CommonUtils.isNullList(list)){
				tcpcrp = (TtCampaignPoseChkRPO)dao.select(tcpcrp).get(0);
			}else {
				throw new RuntimeException("您没有审核权限，请联系系统管理员！");
			}
			
			String campaignNo = request.getParamValue("campaignNo");			//方案编号
			String campaignName = request.getParamValue("campaignName");		//方案名称
			String campaignSubject = request.getParamValue("campaignSubject");	//活动主题
			String campaignType = request.getParamValue("campaignType");		//活动类别
			String startDate = request.getParamValue("startDate");				//开始时间
			String endDate = request.getParamValue("endDate");					//结束时间
			String dealerCode=request.getParamValue("dealerCode");
			String areaId = request.getParamValue("areaId") ;					//业务范围
			String orgId=logonUser.getOrgId().toString();
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps= dao.oemActivitiesSummaryIssuedQuery(areaId, poseId, orgId,campaignNo, campaignName, campaignSubject, campaignType, startDate, endDate, dealerCode, curPage, Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		} catch (RuntimeException e) {
			logger.error(logonUser,e);
			act.setException(e);
		} catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案提报查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动总结提报页面初始化
	 */
	public void showActivitiesSummaryOemCheckDetial(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		ActivitiesCommonDao cdao=ActivitiesCommonDao.getInstance();
		try {
			RequestWrapper request = act.getRequest();
			String campaignId=request.getParamValue("campaignId")==null?"":request.getParamValue("campaignId");
			String executeId=request.getParamValue("executeId")==null?"":request.getParamValue("executeId");
			String camType = CommonUtils.checkNull(request.getParamValue("camType")) ;
			//参数MAP
			Map<String, Object> conMap=new HashMap<String, Object>();
			conMap.put("campaignId", campaignId);
			conMap.put("executeId", executeId);
			conMap.put("costId", "");
			conMap.put("targetId", "");
			
			ActivitiesPlanManageDao dddao = ActivitiesPlanManageDao.getInstance();
			String modelName = dddao.getModelName(campaignId);
			//查品牌
			Map<String, Object> map = dao.selectPinPai();
			String groupName = map.get("GROUP_NAME").toString();
			//查业务范围
			// List<Map<String, Object>> areaList = MaterialGroupManagerDao.getDealerBusiness(logonUser.getPoseId().toString());
			
			//附件列表
			List<Map<String, Object>> attachmentList=cdao.getAttachInfo(executeId);
			// 媒体投放费用
			List<Map<String, Object>> mediaList=cdao.selectMediaCost(conMap);
			// 市场活动费用
			List<Map<String, Object>> capList=cdao.selectCampaignCost(conMap);
			// 活动总结
			Map<String, Object> targetMap=cdao.selectCampaignTarget(conMap);
			//审批信息
			Long orgId = logonUser.getOrgId();
			
			//方案详细信息
			String areaId = "" ;
			Map<String, Object> planMap = null ;
			if(!camType.equals(Constant.CAMPAIGN_TYPE_03.toString())) {
				planMap = cdao.selectCampaignDetial(executeId);
				String dealerIds=planMap.get("DEALER_ID").toString();
				planMap.put("PROD_NAME", modelName);
				areaId=planMap.get("AREA_ID").toString();
				
				List<Map<String, Object>> amountList1 = dao.queryDealerCost(
						dealerIds, areaId); // 经销商推广费用
				List<Map<String, Object>> amountList2 = dao.queryAreaCost(
						dealerIds, areaId); // 区域推广费用
				
				if (amountList1.size() > 0) {
					act.setOutData("amountList1", amountList1.get(0).get(
							"AVAILABLE_AMOUNT"));
				}
				if (amountList2.size() > 0) {
					act.setOutData("amountList2", amountList2.get(0).get(
							"AVAILABLE_AMOUNT"));
				}
				
			} else {
				planMap = cdao.selectSpaceCampaignDetial(executeId);
				String areaOrgId=planMap.get("DEALER_ID").toString();
				planMap.put("PROD_NAME", modelName);
				areaId=planMap.get("AREA_ID").toString();
				String amountList2 = SpacePlanReportDao.getCost(Long.parseLong(areaOrgId), areaId, Constant.COST_TYPE_02) ;
				
				act.setOutData("amountList1", 0) ;
				act.setOutData("amountList2", amountList2) ;
			}
			
			List<Map<String, Object>> amountList3 = dao.queryOemCost(orgId, areaId, Constant.COST_TYPE_03); // 总部市场推广费用
			List<Map<String, Object>> amountList4 = dao.queryOemCost(orgId, areaId, Constant.COST_TYPE_04); // 总部广告费用
			if (amountList3.size() > 0) {
				act.setOutData("amountList3", amountList3.get(0).get(
						"AVAILABLE_AMOUNT"));
			}
			if (amountList4.size() > 0) {
				act.setOutData("amountList4", amountList4.get(0).get(
						"AVAILABLE_AMOUNT"));
			}
			List<Map<String, Object>> checkList = cdao.getCheckInfo(executeId,campaignId);
			List<Map<String, Object>> mycheckList=cdao.getMyCheckInfo(executeId, campaignId);
			
			String type = "" ;
			if(capList.size()>0 ){
				type = capList.get(0).get("COST_TYPE").toString() ;
			}
			if(mediaList.size()>0){
				type = mediaList.get(0).get("COST_TYPE").toString() ;
			}
			act.setOutData("type", type) ;
			
			act.setOutData("camType", camType) ;
			act.setOutData("mycheckList",mycheckList);
			act.setOutData("checkList", checkList);
			act.setOutData("targetMap", targetMap);
			act.setOutData("planMap", planMap);
			act.setOutData("attachmentList", attachmentList);
			act.setOutData("mediaList", mediaList);
			act.setOutData("capList", capList);
			// act.setOutData("areaList", areaList);
			act.setOutData("groupName", groupName);
			act.setOutData("dealerId",logonUser.getDealerId());
			act.setForword(addUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动方案提报新增页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 活动总结区域审批
	 */
	public void activitiesSummaryOemCheck(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String campaignId=request.getParamValue("campaignId")==null?"":request.getParamValue("campaignId");
			String executeId=request.getParamValue("executeId")==null?"":request.getParamValue("executeId");
			String flag=request.getParamValue("flag")==null?"":request.getParamValue("flag");
			String []fjids = request.getParamValues("fjids");
			String camType = CommonUtils.checkId(request.getParamValue("camType")) ;
			String checkDesc=request.getParamValue("checkDesc");
			String costType = request.getParamValue("costType") ;
			
			TtCampaignPO mypo1=new TtCampaignPO();
			mypo1.setCampaignId(Long.parseLong(campaignId));
			mypo1=(TtCampaignPO) dao.select(mypo1).get(0);
			String areaId=String.valueOf(mypo1.getAreaId());
			//方案总结状态更新
			
			Integer updateLen = 0 ;
			List<TtCampaignExecutePO> tce1 = null ;
			
			if (Constant.CAMPAIGN_TYPE_03.toString().equals(camType)) {
				TtCampaignSpaceExecutePO tcse1 = new TtCampaignSpaceExecutePO() ;
				tcse1.setSpaceId(Long.parseLong(executeId)) ;
				
				TtCampaignSpaceExecutePO tcse2 = new TtCampaignSpaceExecutePO() ;
				
				if("0".equals(flag)){
					tcse2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_09);
				}else{
					tcse2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_10);
					ActivitiesCostOpera aco = new ActivitiesCostOpera() ;				//---
					aco.activeSummaryOpera(areaId, costType, camType) ;
				}
				
				tcse2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcse2.setUpdateBy(logonUser.getUserId());
				
				dao.update(tcse1, tcse2);
				
				if(null==checkDesc){
					checkDesc="";
				}
				TtCampaignSummeryChkPO tcecp = new TtCampaignSummeryChkPO();
				
				String checkId =SequenceManager.getSequence("");
				tcecp.setCheckPositionId(logonUser.getPoseId()) ;
				tcecp.setCheckId(Long.parseLong(checkId));
				tcecp.setExecuteId(Long.parseLong(executeId));
				tcecp.setCheckOrgId(logonUser.getOrgId());
				tcecp.setCheckDate(new Date(System.currentTimeMillis()));
				tcecp.setCheckDesc(checkDesc);
				if("0".equals(flag)){
					tcecp.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_09);
				}else{
					tcecp.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_10);
				}
				tcecp.setCheckUserId(logonUser.getUserId());
				tcecp.setCreateBy(logonUser.getUserId());
				tcecp.setCreateDate(new Date(System.currentTimeMillis()));
				dao.insert(tcecp);
				
				//添加附件
				FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
				act.setOutData("returnValue", 1);
				
				TtCampaignExecutePO tcep1 = new TtCampaignExecutePO();
				tcep1.setCampaignId(Long.parseLong(campaignId)) ;
				
				TtCampaignExecutePO tcep2 = new TtCampaignExecutePO();
				
				if("0".equals(flag)){
					tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_09);
				}else{
					tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_10);
				}
				
				tcep2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcep2.setUpdateBy(logonUser.getUserId());
				
				updateLen = dao.update(tcep1, tcep2);
				
				tce1 = dao.select(tcep1) ;
				
				if(updateLen > 0) {
					List<Map<String, Object>> campaignList = dao.select(tcep1) ;
					
					TtCampaignExecutePO tce = null ;
					for(int i=0; i<updateLen; i++) {
						tce = (TtCampaignExecutePO)campaignList.get(i) ;
						executeId = tce.getExecuteId().toString() ;
						
						tcecp = new TtCampaignSummeryChkPO() ;
						checkId =SequenceManager.getSequence("");
						
						tcecp.setCheckPositionId(logonUser.getPoseId()) ;
						tcecp.setCheckId(Long.parseLong(checkId));
						tcecp.setExecuteId(Long.parseLong(executeId));
						tcecp.setCheckOrgId(logonUser.getOrgId());
						tcecp.setCheckDate(new Date(System.currentTimeMillis()));
						tcecp.setCheckDesc(checkDesc);
						if("0".equals(flag)){
							tcecp.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_09);
						}else{
							tcecp.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_10);
						}
						tcecp.setCheckUserId(logonUser.getUserId());
						tcecp.setCreateBy(logonUser.getUserId());
						tcecp.setCreateDate(new Date(System.currentTimeMillis()));
						dao.insert(tcecp);
						
						//添加附件
						FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
						act.setOutData("returnValue", 1);
					}
				}
			} else {
				TtCampaignExecutePO execonpo=new TtCampaignExecutePO();
				execonpo.setExecuteId(new Long(executeId));
				TtCampaignExecutePO exepo=new TtCampaignExecutePO();
				
				if(null!=flag&&"0".equals(flag)){
					exepo.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_09);
				}else{
					exepo.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_10);
					ActivitiesCostOpera aco = new ActivitiesCostOpera() ;				//---
					aco.activeSummaryOpera(areaId, costType, camType) ;
				}
				exepo.setUpdateBy(logonUser.getUserId());
				exepo.setUpdateDate(new Date());
				dao.update(execonpo, exepo);
			
			
				//添加审核明细信息,MARKET_CHECK_STATUS_ 不能区分是方案审批还是总结审批，表中也没有审批类型,如果重新定义审批结果，那么需要区域/总部 总结审批 通过/驳回
				if(null==checkDesc){
					checkDesc="";
				}
				TtCampaignSummeryChkPO tcecp = new TtCampaignSummeryChkPO();
				String checkId =SequenceManager.getSequence("");
				tcecp.setCheckPositionId(logonUser.getPoseId()) ;
				tcecp.setCheckId(Long.parseLong(checkId));
				tcecp.setExecuteId(Long.parseLong(executeId));
				tcecp.setCheckOrgId(logonUser.getOrgId());
				tcecp.setCheckDate(new Date(System.currentTimeMillis()));
				tcecp.setCheckDesc(checkDesc);
				if("0".equals(flag)){
					tcecp.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_09);
				}else{
					tcecp.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_10);
				}
				tcecp.setCheckUserId(logonUser.getUserId());
				tcecp.setCreateBy(logonUser.getUserId());
				tcecp.setCreateDate(new Date(System.currentTimeMillis()));
				dao.insert(tcecp);
				
				//附件添加
				FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
			}
			
			if(!"0".equals(flag)){
				//更新媒体投放费用和市场活动费用
				// Enumeration<String> enumeration = request.getParamNames();
				String[] cam = request.getParamValues("CAM") ;
				String[] med = request.getParamValues("MED") ;
				String[] costId1 = request.getParamValues("costId1") ;
				String[] costId2 = request.getParamValues("costId2") ;
				String camCostId="";
				String medCostId="";
				// String tmp="";
				// int i = 0 ;
				// int j = 0 ;
				int camLen = 0 ;
				if (cam != null) {
					camLen = cam.length ;
				}
				int medLen = 0 ;
				if (med != null) {
					medLen = med.length ;
				}
				for (int n=0; n<camLen; n++) {
					camCostId = costId1[n];
					String camItemCost = cam[n] ;
					
					TtCamCampaignCostPO conpo=new TtCamCampaignCostPO();
					conpo.setCostId(new Long(camCostId));
					TtCamCampaignCostPO po=new TtCamCampaignCostPO();
					po.setItemCost(new Double(camItemCost));
					po.setUpdateBy(logonUser.getUserId());
					po.setUpdateDate(new Date());
					
					dao.update(conpo, po);
					
					for(int i=0; i<updateLen; i++) {
						executeId = tce1.get(i).getExecuteId().toString() ;
						
						conpo=new TtCamCampaignCostPO();
						conpo.setExecuteId(Long.parseLong(executeId));
						conpo.setSpaceCostId(Long.parseLong(camCostId)) ;
						po=new TtCamCampaignCostPO();
						po.setItemCost(new Double(camItemCost));
						po.setUpdateBy(logonUser.getUserId());
						po.setUpdateDate(new Date());
						
						dao.update(conpo, po);
					}
				}
				
				for (int m=0; m<medLen; m++) {
					medCostId = costId2[m] ;
					String medItemCost = med[m];
					
					TtCamMediaCostPO conpo=new TtCamMediaCostPO();
					conpo.setCostId(new Long(medCostId));
					TtCamMediaCostPO po=new TtCamMediaCostPO();
					po.setItemCost(new Double(medItemCost));
					po.setUpdateBy(logonUser.getUserId());
					po.setUpdateDate(new Date());
					
					dao.update(conpo, po);
					
					for(int i=0; i<updateLen; i++) {
						executeId = tce1.get(i).getExecuteId().toString() ;
						
						conpo=new TtCamMediaCostPO();
						conpo.setExecuteId(Long.parseLong(executeId));
						conpo.setSpaceCostId(Long.parseLong(medCostId)) ;
						po=new TtCamMediaCostPO();
						po.setItemCost(new Double(medItemCost));
						po.setUpdateBy(logonUser.getUserId());
						po.setUpdateDate(new Date());
						
						dao.update(conpo, po);
					}
				}
			}
			act.setOutData("returnValue", 1);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动方案总结提报");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
}
